package com.gingko.duominuo.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import androidx.core.view.GravityCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.gingko.duominuo.R
import com.gingko.duominuo.constants.PAGE_SIZE
import com.gingko.duominuo.data.Resource
import com.gingko.duominuo.data.model.TaskVo
import com.gingko.duominuo.data.model.Value
import com.gingko.duominuo.data.request.CreateTaskReqVo
import com.gingko.duominuo.data.request.TaskReqVo
import com.gingko.duominuo.databinding.FragmentTaskBinding
import com.gingko.duominuo.ui.adapter.TaskAdapter
import com.gingko.duominuo.ui.widget.DefaultItemDecoration
import com.gingko.duominuo.ui.widget.EmptyLayout
import com.gingko.duominuo.utils.singleClick
import com.gingko.duominuo.utils.toast
import com.gingko.duominuo.viewmodel.BaseViewModel
import com.gingko.duominuo.viewmodel.TaskViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class TaskFragment : BaseFragment(), OnRefreshLoadMoreListener {
    private val mViewBinding: FragmentTaskBinding by lazy {
        FragmentTaskBinding.inflate(
            layoutInflater
        )
    }
    private val mViewModel by viewModels<TaskViewModel>()
    private val taskVos by lazy { mutableListOf<TaskVo>() }
    private val taskAdapter by lazy { TaskAdapter(requireContext(), taskVos) }
    private val taskReqVo by lazy { TaskReqVo() }
    private lateinit var lastCheckOrderBy: RadioButton
    private val filterFragment by lazy { TaskFilterFragment.newInstance() }

    companion object {
        @JvmStatic
        fun newInstance() = TaskFragment()
    }

    override fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View {
        return mViewBinding.root
    }

    override fun getViewModel(): BaseViewModel {
        return mViewModel
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            onRefresh(mViewBinding.refreshLayout)
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        lastCheckOrderBy = mViewBinding.rbStart
        filterFragment.callback = object : TaskFilterFragment.Callback {

            override fun onConfirmFilter(project: Value?, platform: Value?, taskType: Value?) {
                taskReqVo.proj = project?.name
                taskReqVo.app = platform?.name
                taskReqVo.task = taskType?.name
                val textArr = arrayOf(project?.desc, platform?.desc, taskType?.desc)
                val title = textArr.filterNotNull().joinToString("-")
                if (title.isEmpty()){
                    mViewBinding.titleView.title = "任务"
                }else{
                    mViewBinding.titleView.title = title
                }

                onRefresh(mViewBinding.refreshLayout)
                mViewBinding.drawerLayout.closeDrawer(GravityCompat.END)
            }

            override fun onResetFilter() {
                taskReqVo.proj = null
                taskReqVo.app = null
                taskReqVo.task = null
                mViewBinding.titleView.title = "任务"
                onRefresh(mViewBinding.refreshLayout)
            }
        }
        childFragmentManager.beginTransaction().add(R.id.fl_container, filterFragment).commit()
        mViewBinding.rbStart.singleClick { resetOrderByStatus(it) }
        mViewBinding.rbEnd.singleClick { resetOrderByStatus(it) }
        mViewBinding.rbAmount.singleClick { resetOrderByStatus(it) }
        mViewBinding.tvFilter.singleClick { mViewBinding.drawerLayout.openDrawer(GravityCompat.END) }
        mViewBinding.refreshLayout.setOnRefreshLoadMoreListener(this)
        mViewBinding.refreshLayout.setEnableLoadMore(false)
        taskAdapter.callback = object : TaskAdapter.Callback {
            override fun onReceiveTask(taskVo: TaskVo) {
                mViewModel.createTaskOrder(
                    CreateTaskReqVo(
                        taskVo.proj,
                        taskVo.app,
                        taskVo.task,
                        taskVo.job_id
                    )
                )
            }
        }
        mViewBinding.rcvTask.addItemDecoration(
            DefaultItemDecoration(
                requireContext(),
                LinearLayoutManager.VERTICAL,
                1
            )
        )
        mViewBinding.rcvTask.adapter = taskAdapter
        mViewModel.getTaskFilter()
        mViewBinding.refreshLayout.autoRefresh()
        observeData()
    }

    private fun observeData() {
        mViewModel.taskLiveData.observe(owner = this) {
            mViewBinding.refreshLayout.closeHeaderOrFooter()
            when (it) {
                is Resource.Success -> {
                    if (taskReqVo.page == 1 && it.data.isNullOrEmpty()) {
                        mViewBinding.emptyLayout.show(EmptyLayout.NO_DATA)
                    } else {
                        mViewBinding.emptyLayout.hide()
                    }
                    if (taskReqVo.page == 1) {
                        taskVos.clear()
                    }
                    it.data?.let { records ->
                        mViewBinding.refreshLayout.setNoMoreData(records.size < PAGE_SIZE)
                        mViewBinding.refreshLayout.setEnableLoadMore(records.size == PAGE_SIZE)
                        taskVos.addAll(records)
                    }
                    taskAdapter.setEnableReceiveTask(!mViewModel.noTaskOrder)
                    taskAdapter.notifyDataSetChanged()
                }
                is Resource.Error -> {
                    taskReqVo.page--
                    mViewBinding.emptyLayout.show(EmptyLayout.LOAD_ERROR)
                    it.throwable?.message?.toast()
                }
            }
        }

        mViewModel.createTaskOrderLiveData.observe(owner = this) {
            when (it) {
                is Resource.Success -> {
                    "领取成功".toast()
                    onRefresh(mViewBinding.refreshLayout)
                }
                is Resource.Error -> {
                    it.throwable?.message?.toast()
                }
            }
        }
        mViewModel.taskFilterLiveData.observe(owner = this) {
            if (it is Resource.Success) {
                it.data?.let { it1 -> filterFragment.updateData(it1) }
            }
        }
    }

    private fun resetOrderByStatus(radioButton: RadioButton) {
        when (radioButton.id) {
            R.id.rb_start -> taskReqVo.orderby = "begin_time"
            R.id.rb_end -> taskReqVo.orderby = "end_time"
            R.id.rb_amount -> taskReqVo.orderby = "task_count"
        }
        if (radioButton.id != lastCheckOrderBy.id) {
            lastCheckOrderBy.isSelected = false
            lastCheckOrderBy = radioButton
        } else {
            radioButton.isSelected = !radioButton.isSelected
        }
        taskReqVo.sort = if (radioButton.isSelected) "asc" else "desc"
        onRefresh(mViewBinding.refreshLayout)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        taskReqVo.page++
        mViewModel.getTasks(taskReqVo)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        taskReqVo.page = 1
        mViewModel.getTasks(taskReqVo)
    }


}